//
//  HNSubmitProblemController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2017/1/5.
//  Copyright © 2017年 好牛. All rights reserved.
//

#import "HNSubmitProblemController.h"
#import "ZLPhotoPickerViewController.h"
#import "ZLPhotoAssets.h"


#define gap 5
#define imageW (kScreen_Width - 5*gap)/4
#define imageH (kScreen_Width - 5*gap)/4

@interface HNSubmitProblemController ()<UITextViewDelegate>

@property (nonatomic,strong)NSMutableArray *imageNames;

@property (nonatomic,strong)NSString *imagesStr;

@property (nonatomic,strong)UIView *imagesView;

@end

@implementation HNSubmitProblemController


-(void)choiceImageAction:(UIButton *)btn{
    ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init];
    // MaxCount, Default = 9
    pickerVc.maxCount = 6;
    // Jump AssetsVc
    pickerVc.status = PickerViewShowStatusCameraRoll;
    // Filter: PickerPhotoStatusAllVideoAndPhotos, PickerPhotoStatusVideos, PickerPhotoStatusPhotos.
    pickerVc.photoStatus = PickerPhotoStatusPhotos;
    // Recoder Select Assets
    pickerVc.selectPickers = _imageNames;
    // Desc Show Photos, And Suppor Camera
    pickerVc.topShowPhotoPicker = YES;
    pickerVc.isShowCamera = YES;
    // CallBack
    pickerVc.callBack = ^(NSArray<ZLPhotoAssets *> *status){
        [_imageNames removeAllObjects];
        _imageNames=status.mutableCopy ;
        
        NSLog(@"%@",_imageNames);
        
        [self reloadScrollView];
    };
    [pickerVc showPickerVc:self];
}

-(void)reloadScrollView{
    
    [self setImagesViewContent];
    //重新设置按钮的位置
    [self setChoiceImageBtnFrame];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"提问";
}

-(void)drawView{
    //添加点击按钮---添加一个按钮
    UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [clickBtn setTitle:@"提交" forState:UIControlStateNormal];
    [clickBtn setFont:[UIFont systemFontOfSize:15]];
    [clickBtn setTitleColor:RGBJ(80) forState:UIControlStateNormal];
    [clickBtn setTitleColor:RGBJ(80) forState:UIControlStateSelected];
    
    clickBtn.frame = CGRectMake(0,0,40,20);
    [clickBtn addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:clickBtn];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    
    
    self.problemDetail.delegate = self;
    
    
    
    //设置选择图片格式
    CGFloat imagesScrollViewH = gap + 2*(imageH+gap);
    CGRect frame =  _imagesScrollView.frame;
    frame.size.height = imagesScrollViewH;
    _imagesScrollView.frame = frame;
    _imagesScrollView.contentSize = frame.size;
    [self.view addSubview:_imagesScrollView];
    
    //加一个放图片的View
    _imagesView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _imagesScrollView.frame.size.width, _imagesScrollView.frame.size.height)];
    [_imagesScrollView addSubview:_imagesView];
    
    _choiceImageBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [_choiceImageBtn setFont:[UIFont systemFontOfSize:15]];
    [_choiceImageBtn setBackgroundColor:[UIColor whiteColor]];
    [_choiceImageBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _choiceImageBtn.frame = CGRectMake(gap,gap,imageW,imageW);
    [_choiceImageBtn setBackgroundImage:[UIImage imageNamed:@"main_photochoose.png"] forState:UIControlStateNormal];
    [_choiceImageBtn addTarget:self action:@selector(choiceImageAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self setChoiceImageBtnFrame];
    
}

#pragma mark - 添加添加图片
-(void)setImagesViewContent{
    NSInteger count = _imageNames.count;
    
    for (int i = 0; i<6; i++) {
        UIImageView *imageView = (UIImageView *)[_imagesView viewWithTag:i];
        [imageView removeFromSuperview];
    }
    [_imagesView removeFromSuperview];
    
    _imagesView.frame = CGRectMake(0, 0, _imagesScrollView.frame.size.width, _imagesScrollView.frame.size.height);
    [_imagesScrollView addSubview:_imagesView];
    
    for (NSInteger i = 0; i<count; i++) {
        CGFloat imageX = gap + (gap + imageW)*(i%4);
        CGFloat imageY = gap + (gap + imageW)*(i/4);
        
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
        imageView.tag = i;
        ZLPhotoAssets *photoAssetc = _imageNames[i];
        [imageView setImage:photoAssetc.originImage];
        [_imagesView addSubview:imageView];
    }
}

#pragma mark - 添加选择图片按钮
-(void)setChoiceImageBtnFrame{
    NSInteger count = _imageNames.count;
    CGFloat btnX = gap + (gap + imageW)*(count%4);
    CGFloat btnY = gap + (gap + imageW)*(count/4);
    
    CGRect frame =  _choiceImageBtn.frame;
    frame.origin.x = btnX;
    frame.origin.y = btnY;
    _choiceImageBtn.frame = frame;
    [_imagesScrollView addSubview:_choiceImageBtn];
}


#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView{
    if (_problemDetail.text.length > 0) {
        [self.prompt setHidden:YES];
    }else{
        [self.prompt setHidden:NO];
    }
}


#pragma mark - 问题提交
-(void)submitAction:(UIButton *)btn{
    if ([AppConfig isNULL:_problemTitle.text]) {
        [self showHint:@"请添加您想提交的问题"];
    }
    if ([AppConfig isNULL:_problemDetail.text]) {
        [self showHint:@"请添加您想提交的问题详情"];
    }
    if (_imageNames.count==0) {
        [self showHint:@"请添加问题图片"];
    }
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:url_update_userInfo_image parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSMutableArray *imageFileArr = [[NSMutableArray alloc]init];
        //循环加入上传图片
        
        for(int i = 0; i< _imageNames.count ; i++){
            //要上传的图片
            ZLPhotoAssets *photoAssets = _imageNames[i];
            //压缩图片
            __block UIImage * changeImage = [self compressImage:photoAssets.originImage toTargetWidth:333];
            
            NSData *data = UIImagePNGRepresentation(changeImage);
            //得到图片的data
            NSMutableString *imgbody = [[NSMutableString alloc] init];
            //此处循环添加图片文件
            //添加图片信息字段
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            // 设置时间格式
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@第%d张.png", str,i];
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
        }
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印下上传进度
        NSLog(@"上传进度");
        NSLog(@"%@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功
        NSLog(@"上传成功");
        NSError *error;
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        
        NSLog(@"%@",data);
        
        
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            return;
        }
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        
        
        if ([result isEqualToString:@"1"]) {
            _imagesStr = [NSString stringWithFormat:@"%@",[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",_imagesStr);
            
            
            [self submitProblemAction];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败
        NSLog(@"上传失败");
        NSLog(@"%@",error.description);
    }];
    
    
}

//压缩图片
- (UIImage *)compressImage:(UIImage *)sourceImage toTargetWidth:(CGFloat)targetWidth {
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    NSLog(@"width = %f,height = %f",width,height);
    
    CGFloat targetHeight = (targetWidth / width) * height;
    NSLog(@"targetWidth = %f targetHeight = %f",targetWidth,targetHeight);
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}


//提交最终方法
-(void)submitProblemAction{
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    [param setObject:_problemTitle.text forKey:@"briefContent"];
    [param setObject:_problemDetail.text forKey:@"content"];
    [param setObject:_imagesStr forKey:@"image"];
    
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_problem_add parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"提交问题失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
         
            [self.navigationController popViewControllerAnimated:YES];
            [self showHint:@"问题发布成功"];
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"提交问题失败"];
        
    }];
    
}


@end
